﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DauGiaApp.Models;
using System.Net.Configuration;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using DauGiaApp;

using System.Web.Mvc;
using DauGiaApp.Models;
using Microsoft.Web.Helpers;
using System.Web.Routing;
namespace DauGiaApp.Controllers
{
    public class TaiKhoanController : Controller
    {
        //
        // GET: /TaiKhoan/
        DauGiaEntities data = new DauGiaEntities();
        
        public ActionResult Index()
        {
            
            DauGiaEntities daugia = new DauGiaEntities();
            var lsTaiKhoan = daugia.TaiKhoans.ToList();
            return View(lsTaiKhoan);
        }

        public ActionResult DanhSach()
        {
            DauGiaEntities daugia = new DauGiaEntities();
            var lsTaiKhoan = daugia.TaiKhoans.ToList();
            return View(lsTaiKhoan);
        }
        public ActionResult DangKy()
        {
            
            return View();
        }

        public ActionResult DangNhap()
        {
            return View();
        }

        [HttpPost]
        public ActionResult DangKy(TaiKhoan tk)
        {   
            tk.MaLoaiTaiKhoan = 1;                                    
            tk.TrangThai = 1;
            data.TaiKhoans.AddObject(tk);
            data.SaveChanges();
            RouteValueDictionary rvd = new RouteValueDictionary();
            rvd.Add("noiDung", "Chúc mừng bạn đã đăng ký tài khoản thành công!");
            return Content("đăng ký thành công");
            
        }

        [HttpPost]
        public ActionResult Login(TaiKhoan tk)
        {
            var query = from n in data.TaiKhoans
                        where n.TenTaiKhoan == tk.TenTaiKhoan && n.MatKhau == tk.MatKhau
                        select n;

            if (query.Count() > 0)
                return RedirectToAction("Index", "Home");
            else
                return View();
        }

        // quoc bao
        public ActionResult DangXuat()
        {
            Session["user"] = null;

            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        public ActionResult DangNhap(string TenTaiKhoan, string MatKhau)
        {
            try
            {
                var query = from n in data.TaiKhoans
                            where n.TenTaiKhoan == TenTaiKhoan && n.MatKhau == MatKhau
                            select n;
                if (query != null)
                {
                    TaiKhoan tk = query.ToList().ElementAt(0);
                    Session.Timeout = 10;
                    Session.Add("user", tk);
                    HttpCookie us = new HttpCookie("TenTaiKhoan", TenTaiKhoan);
                    Request.Cookies.Add(us);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    return View();
                }
            }
            catch (Exception ex)
            {

                return View();
            }


        }
       
        public ActionResult CapNhat()
        {

            TaiKhoan tk = (from n in data.TaiKhoans
                           where (n.TenTaiKhoan == Session["user"].ToString())
                           select n).Single();
            return View(tk);
        }
        // end quoc bao

        public ActionResult CheckCaptCha()
        {
            
            if (ReCaptcha.Validate(privateKey: "6LesKsUSAAAAABKWPwwcbj6sI_GiVNlFjnIluGhV"))
            {
                return Json(new { IsOk = "yes" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new { IsOk = "no" }, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult ThongBao(String noiDung)
        {
            return View(noiDung);
        }
        public ActionResult ThongTinTaiKhoan()
        {

            TaiKhoan currentUser = (TaiKhoan)Session["user"];
            return View(currentUser);
        }
        //Ngọc Thủy tuần 17
        public ActionResult ChiTietTaiKhoan()
        {
            TaiKhoan currentUser = (TaiKhoan)Session["user"];
            if (currentUser == null)            {
                
                return RedirectToAction("DangNhap", "TaiKhoan");
            }
            return View(currentUser);
            // return View();
        }
         [HttpPost]
        public ActionResult CapNhatThongTin(ThongTinTaiKhoan thongTin)
        {
            
            //if (thongTin == null) return "";
            TaiKhoan currentUser = (TaiKhoan)Session["user"];
            if (currentUser == null)
            {
                return RedirectToAction("DangNhap", "TaiKhoan");
            }
            ThongTinTaiKhoan tt = currentUser.ThongTinTaiKhoan;
            var query = from n in data.ThongTinTaiKhoans
                        where n.MaThongTinTK == tt.MaThongTinTK
                        select n;
             
            if (query.Count() > 0)
            {
                ThongTinTaiKhoan thongTinCu = query.Single();
                if (thongTin.GioiTinh != null)
                    thongTinCu.GioiTinh = thongTin.GioiTinh;
                if (thongTin.HoTen != null && thongTin.HoTen.Length != 0)
                    thongTinCu.HoTen = thongTin.HoTen;
                if (thongTin.MaTheTinhDung != null && thongTin.MaTheTinhDung.Length != 0)
                    thongTinCu.MaTheTinhDung = thongTin.MaTheTinhDung;
                if (thongTin.NgaySinh != null)
                    thongTinCu.NgaySinh = thongTin.NgaySinh;
                if (thongTin.NoiSinh != null && thongTin.NoiSinh.Length > 0)
                    thongTinCu.NoiSinh = thongTin.NoiSinh;
                if (thongTin.DiaChi != null && thongTin.DiaChi.Length > 0)
                    thongTinCu.DiaChi = thongTin.DiaChi;
                if (thongTin.SoDienThoai != null && thongTin.SoDienThoai.Length > 0)
                    thongTinCu.SoDienThoai = thongTin.SoDienThoai;

                data.SaveChanges();
                var usquery = from n in data.TaiKhoans
                              where n.TenTaiKhoan == currentUser.TenTaiKhoan && n.MatKhau == currentUser.MatKhau
                              select n;

                if (usquery.Count() > 0)
                {
                    currentUser = usquery.Single();
                    Session.Timeout = 100;
                    //Session.Add("user", currentUser);
                    Session.Remove("user");
                    Session.Add("user", currentUser);
                    //  return RedirectToAction("Index", "Home");
                }

                return Content("cập nhật thông tin thành công");
            }
            return Content("Không cập nhật được");

        }

         public ActionResult GoiEmailXacNhanMatKhau(PhucHoiMatKhauModel model)
         {
             if (model == null) return View();
             if (model.Email == null) return View();
             var users = from n in data.TaiKhoans
                         where n.Email == model.Email
                         select n;
             if (users.Count() == 0)
             {
                 Response.Write("<script>alert('email khong hop le')</script>");
                 return View();
             }

             MailMessage msg = new MailMessage();
             msg.IsBodyHtml = true;
             msg.From = new MailAddress("cui_bap_dang_a@yahoo.com.vn", "D4 Group website");
             msg.To.Add(new MailAddress(model.Email));
             msg.Subject = "D4 Group Website";
             string newPassword = GeneratePassword();
             msg.Body = "hi " + "this is your new password from D4 website:" + newPassword;
             SmtpClient client = new SmtpClient("smtp.mail.yahoo.com", 25);
             client.Credentials = new NetworkCredential("cui_bap_dang_a", "03021990");
             client.EnableSsl = false;
             client.Send(msg);
             if (users.Count() == 1)
             {
                 TaiKhoan curUser = users.Single();
                 curUser.MatKhau = newPassword;
                 data.SaveChanges();
             }
             else
             {
                 TaiKhoan curUser = users.ToList()[0];
                 curUser.MatKhau = newPassword;
                 data.SaveChanges();
             }
             Response.Write("<script>alert('mật khẩu mới đã được gởi đến địa chỉ email cua bạn, xin vui lòng kiểm tra lại')</script>");


             #region MyRegion
             //Microsoft.Office.Interop.Outlook.Application oApp = new Application();

             ////Create the new message by using the simplest approach.
             //Microsoft.Office.Interop.Outlook.MailItem oMsg = (MailItem)oApp.CreateItem(OlItemType.olMailItem);

             ////Add a recipient.
             //// TODO: Change the following recipient where appropriate.
             //Recipient oRecip = (Recipient)oMsg.Recipients.Add(model.Email);
             //oRecip.Resolve();

             ////Set the basic properties.
             //oMsg.Subject = "D4Group Website, update password information";
             //string newPassword = GeneratePassword();
             //oMsg.Body = "this is your new password: " + newPassword;
             //oMsg.Save();
             //oMsg.Send();
             //var usquery = from n in data.TaiKhoans
             //              where n.Email == model.Email
             //              select n;

             //if (usquery.Count() > 1)
             //{
             //    TaiKhoan currentUser = (TaiKhoan)(usquery.ToList()[0]);
             //    currentUser.MatKhau = newPassword;
             //}
             //else if (usquery.Count() == 1)
             //{
             //    TaiKhoan currentUser = usquery.Single();
             //    currentUser.MatKhau = newPassword;
             //}
             ////Explicitly release objects.
             //data.SaveChanges();
             //oRecip = null;
             ////oAttach = null;
             //oMsg = null;
             //oApp = null; 
             #endregion
             return View();
         }
         public string GeneratePassword()
         {
             Random rand = new Random();
             string characters = "0123456789abcdefghijklmnopqrstuvxyABCDEFGHIJKLMNOPQRSTUVXY";
             int numChar = characters.Length;
             string newPass = "";
             for (int i = 0; i < 10; ++i)
             {
                 int index = rand.Next(numChar);
                 index = index % numChar;
                 newPass += characters[index];
             }
             return newPass;
         }

         public ActionResult CacPhienDauGiaDaThamGia()
         {
             TaiKhoan currUser = (TaiKhoan)Session["user"];
             if (currUser == null) return View();
             var dsChiTietDauGia = from n in data.ChiTietDauGias
                                   where n.MaTaiKhoan == currUser.MaTaiKhoan
                                   select n;
             List<DauGia> dsDauGia = new List<DauGia>();
             // co chi tiet dau gia
             if (dsChiTietDauGia != null && dsChiTietDauGia.Count() > 0)
             {
                 for (int i = 0; i < dsChiTietDauGia.Count(); i++)
                 {
                     var query = data
                                 .DauGias
                                 .Where(dg => dg.MaDauGia == dsChiTietDauGia.ElementAt(i).MaDauGia
                                         && dg.ThoiGianKetThuc < DateTime.Now)
                                  .SingleOrDefault();
                     //var query = from n in data.DauGias
                     //            where n.MaDauGia == dsChiTietDauGia
                     //                               .ElementAt(i)
                     //                               .MaDauGia && n.ThoiGianKetThuc <= DateTime.Now
                     //            select n;
                     //if (query == null) continue;
                     //for (int j = 0; j < query.Count(); ++j)
                     //{
                     if(query != null)
                         dsDauGia.Add(query);
                     //}
                 }
                 
             }else // khong co chi tiet dau gia
             {
                 return View();
             }
              
             if (dsDauGia.Count() > 0)
             {
                 dsDauGia.Distinct();
                 return View(dsDauGia.GetEnumerator());
             }
             else return View();
         }
         public ActionResult ChiTietDauGia(string id)
         {
             int madg = Int32.Parse(id);
             var query = from dg in data.DauGias
                         where dg.MaDauGia == madg
                         select dg;
             if (query.Count() > 0)
                 return View(query.ToList().ElementAt(0));
             return View();
         }
         public ActionResult DangDauGia()
         {
             var dsDauGia = from n in data.DauGias
                            where n.SanPham.TinhTrangSanPham.MaTinhTrangSanPham == 1
                            select n;
             return View(dsDauGia);
         }
    }
}
